/**
 * 微前端应用配置
 */

export interface MicroAppMapping {
  /** 应用名称 */
  name: string;
  /** 路由前缀 */
  prefix: string;
  /** 优先级（数字越大优先级越高），用于处理路径冲突 */
  priority?: number;
  /** 本地开发端口 */
  port?: number;
  /** 环境变量键名 */
  envKeys?: string[];
  /** 组件匹配模式（用于识别 component 字段） */
  componentPatterns?: string[];
}

/**
 * 微前端应用映射配置
 * 
 * 匹配规则：
 * 1. 优先使用 componentPatterns 配置进行精确匹配
 * 2. 其次使用默认规则（根据 prefix 匹配 component 字段）
 * 3. 最后根据路径前缀匹配
 */
export const MICRO_APP_MAPPINGS: MicroAppMapping[] = [
  {
    name: 'login-app',
    prefix: '/login',
    priority: 200,
    port: 3003,
    envKeys: ['VITE_APP_LOGIN_APP_URL', 'VITE_LOGIN_APP_URL'],
  },
  {
    name: 'dashboard-app',
    prefix: '/dashboard',
    priority: 150,
    port: 3007,
    envKeys: ['VITE_APP_DASHBOARD_APP_URL', 'VITE_DASHBOARD_APP_URL'],
  },
  {
    name: 'system-app',
    prefix: '/system',
    priority: 100,
    port: 3005,
    envKeys: ['VITE_APP_SYSTEM_APP_URL', 'VITE_SYSTEM_APP_URL'],
  },
  {
    name: 'workflow-app',
    prefix: '/workflow',
    priority: 95,
    port: 3008,
    envKeys: ['VITE_APP_WORKFLOW_APP_URL', 'VITE_WORKFLOW_APP_URL'],
  },
  {
    name: 'tenant-app',
    prefix: '/tenant',
    priority: 90,
    port: 3009,
    envKeys: ['VITE_APP_TENANT_APP_URL', 'VITE_TENANT_APP_URL'],
    componentPatterns: ['tenant'], // 匹配包含 'tenant' 的 component（包括 tenantPackage）
  },
  {
    name: 'tool-app',
    prefix: '/tool',
    priority: 80,
    port: 3006,
    envKeys: ['VITE_APP_TOOL_APP_URL', 'VITE_TOOL_APP_URL'],
    componentPatterns: ['tool'], // 匹配包含 'tool' 的 component
  },
  {
    name: 'monitor-app',
    prefix: '/monitor',
    priority: 70,
    port: 3010,
    envKeys: ['VITE_APP_MONITOR_APP_URL', 'VITE_MONITOR_APP_URL'],
  },
  {
    name: 'deploy-manager',
    prefix: '/deploy',
    priority: 60,
    port: 3011,
    envKeys: ['VITE_APP_DEPLOY_MANAGER_URL', 'VITE_DEPLOY_MANAGER_URL'],
  },
];

/**
 * 根据菜单项的 component 字段判断所属微应用
 * 规则：component 字段通常包含应用名称，如 'system/user/index' 或 '/system/user/index'
 */
export const getMicroAppByPath = (path: string, component?: string): MicroAppMapping | null => {
  // 🔧 调试日志：查看所有匹配过程
  if (component && (component.includes('tenant') || path.includes('tenant'))) {
    console.log('🔍 [MicroAppConfig] Tenant 相关组件匹配开始:', {
      path,
      component,
      componentLower: component.toLowerCase(),
      timestamp: Date.now()
    });
  }
  
  // 优先根据 component 字段判断
  if (component) {
    const componentLower = component.toLowerCase();
    
    // 按优先级排序
    const sortedApps = [...MICRO_APP_MAPPINGS].sort((a, b) => (b.priority || 0) - (a.priority || 0));
    
    for (const app of sortedApps) {
      // 移除前缀的斜杠进行匹配
      const appName = app.prefix.replace(/^\//, '');
      
      // 🔧 调试日志：查看每个应用的匹配过程
      if (component && (component.includes('tenant') || path.includes('tenant'))) {
        console.log(`🔍 [MicroAppConfig] 检查应用 ${app.name}:`, {
          appName,
          componentPatterns: app.componentPatterns,
          componentLower,
          priority: app.priority
        });
      }
      
      // 1. 优先使用 componentPatterns 配置
      if (app.componentPatterns) {
        for (const pattern of app.componentPatterns) {
          if (componentLower.includes(pattern.toLowerCase())) {
            if (component && (component.includes('tenant') || path.includes('tenant'))) {
              console.log('✅ [MicroAppConfig] Tenant 通过 componentPatterns 匹配:', {
                app: app.name,
                pattern,
                componentLower
              });
            }
            return app;
          }
        }
      }
      
      // 2. 默认规则：检查 component 是否包含应用名称
      if (componentLower.includes(`/${appName}/`) || 
          componentLower.startsWith(`${appName}/`) ||
          componentLower.includes(`-${appName}/`)) {
        if (component && (component.includes('tenant') || path.includes('tenant'))) {
          console.log('✅ [MicroAppConfig] Tenant 通过默认规则匹配:', {
            app: app.name,
            appName,
            componentLower
          });
        }
        return app;
      }
    }
  }
  
  // 如果 component 无法判断，则根据路径前缀判断
  // 按优先级排序
  const sortedApps = [...MICRO_APP_MAPPINGS].sort((a, b) => (b.priority || 0) - (a.priority || 0));
  
  for (const app of sortedApps) {
    // 如果路径已经包含前缀，直接匹配
    if (path.startsWith(app.prefix)) {
      return app;
    }
  }
  
  return null;
};

/**
 * 获取所有微前端路由前缀
 */
export const getAllMicroAppPrefixes = (): string[] => {
  return MICRO_APP_MAPPINGS.map(app => app.prefix);
};

/**
 * 根据服务前缀构建完整路径
 */
export const buildMicroAppPath = (originalPath: string, servicePrefix?: string): string => {
  // 🔧 调试日志：查看路径构建过程
  if (originalPath.includes('tenant') || servicePrefix === 'tenant-app') {
    console.log('🔍 [MicroAppConfig] buildMicroAppPath 开始:', {
      originalPath,
      servicePrefix,
      timestamp: Date.now()
    });
  }
  
  if (!servicePrefix) {
    if (originalPath.includes('tenant')) {
      console.log('❌ [MicroAppConfig] 没有 servicePrefix，返回原始路径:', originalPath);
    }
    return originalPath;
  }

  const app = MICRO_APP_MAPPINGS.find(app => app.name === servicePrefix);
  if (!app) {
    if (originalPath.includes('tenant')) {
      console.log('❌ [MicroAppConfig] 找不到应用配置，返回原始路径:', originalPath);
    }
    return originalPath;
  }

  const { prefix } = app;
  
  // 如果路径已经包含前缀，直接返回
  if (originalPath.startsWith(prefix)) {
    if (originalPath.includes('tenant')) {
      console.log('✅ [MicroAppConfig] 路径已包含前缀，直接返回:', originalPath);
    }
    return originalPath;
  }

  // 构建完整路径
  const result = `${prefix}${originalPath.startsWith('/') ? '' : '/'}${originalPath}`;
  
  if (originalPath.includes('tenant')) {
    console.log('🔧 [MicroAppConfig] 构建完整路径:', {
      originalPath,
      prefix,
      result
    });
  }
  
  return result;
};

/**
 * 从微前端路径中移除前缀，用于菜单匹配
 */
export const removeMicroAppPrefix = (path: string): string => {
  const prefixes = getAllMicroAppPrefixes();
  
  for (const prefix of prefixes) {
    if (path.startsWith(prefix)) {
      return path.replace(new RegExp(`^${prefix}`), '') || '/';
    }
  }
  
  return path;
};

